package com.plan.controller.card;

import com.plan.base.constant.BaseCode;
import com.plan.base.constant.Constant;
import com.plan.base.entity.Result;
import com.plan.controller.user.response.UserVO;
import com.plan.controller.card.request.DelPointProductReq;
import com.plan.controller.card.request.PointProductPageListReq;
import com.plan.controller.card.response.PointProductListRes;
import com.plan.entity.card.PointProduct;
import com.plan.service.card.PointProductService;
import com.plan.service.card.TeamService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 积分商城
 * 礼物管理
 *
 * @author zcl
 */
@RestController
@RequestMapping("pointProduct/")
public class PointProductController {
    @Resource
    private TeamService teamService;
    @Resource
    private PointProductService pointProductService;

    @PostMapping(value = "add")
    public Result<Long> add(@RequestBody PointProduct req, HttpServletRequest httpRequest) {
        if (req.getTeamId() == null || req.getSpendPoint() == null || req.getSpendPoint() < 0 || req.getName() == null) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        UserVO user = (UserVO) httpRequest.getAttribute(Constant.USER_KEY);
        if (!teamService.isUserInTeam(req.getTeamId(), user.getId())) {
            return Result.fail(BaseCode.ILLEGAL_OPERATION);
        }
        return pointProductService.add(req, user);
    }

    @PostMapping(value = "delete")
    public Result<Integer> delete(@RequestBody DelPointProductReq req, HttpServletRequest httpRequest) {
        if (req.getId() == null || req.getTeamId() == null) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        UserVO user = (UserVO) httpRequest.getAttribute(Constant.USER_KEY);
        if (!teamService.isUserInTeam(req.getTeamId(), user.getId())) {
            return Result.fail(BaseCode.ILLEGAL_OPERATION);
        }
        return pointProductService.delete(req.getTeamId(), req.getId(), user);
    }

    @PostMapping(value = "list")
    public Result<List<PointProductListRes>> list(@RequestBody PointProductPageListReq req, HttpServletRequest httpRequest) {
        if (req.getTeamId() == null) {
            return Result.fail(BaseCode.PARAM_ERROR);
        }
        if (req.getPageSize() > Constant.CLIENT_MAX_PAGE_SIZE) {
            req.setPageSize(Constant.CLIENT_MAX_PAGE_SIZE);
        }
        UserVO user = (UserVO) httpRequest.getAttribute(Constant.USER_KEY);
        if (!teamService.isUserInTeam(req.getTeamId(), user.getId())) {
            return Result.fail(BaseCode.ILLEGAL_OPERATION);
        }
        return pointProductService.getPageList(req);
    }

}
